const exp = require('express');
const fs = require('fs');
const route = exp.Router();
const common = require('../common');
// 登录
route.post('/api/v1/user/signin', (req, res) => {
    console.log(req.body.password);
    var filename = `users/${req.body.username}.json`;
    fs.exists(filename, (exists) => {
        if (exists) {
            fs.readFile(filename, (err, data) => {
                if (err) {
                    common.send(res, 'signin error', '登录失败！');
                } else {
                    console.log(data.toString());
                    var user = JSON.parse(data.toString());
                    if (req.body.password == user.password) {
                        //   密码相等,登录成功
                        console.log("啦啦啦啦");
                        res.cookie('username', req.body.username);
                         common.send(res, 'success', '登录成功！');
                          
                    }else{
                         common.send(res, 'password error', '密码错误');
                    }

                } 
            })
                }else {
                    // 文件不存在，说明没有该用户
                    common.send(res, 'signin error', '该用户不存在，请注册！');
                }
            })
        })


    // 退出接口
    route.get('/api/user/signout', (req, res) => {
        // 清除cookie
        res.clearCookie('username');
      res.redirect('/');
    })
    // 导出模块
    module.exports = route;





